package kr.hkit.androidcomplete03.ch28;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import kr.hkit.androidcomplete03.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;

public class DownImage extends Activity implements OnClickListener {
	ImageView imageView;
	ProgressDialog progressDlg;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch28_downimage);
		findViewById(R.id.btndraw).setOnClickListener(DownImage.this);
		imageView = (ImageView) findViewById(R.id.result);
	}

	public void onClick(View v) {
		String str = "http://developer.android.com/images/home/kk-hero.jpg";
		new ImageLoadingTask().execute(str);
	}

	private class ImageLoadingTask extends
			android.os.AsyncTask<String, Void, Bitmap> {

		protected void onPreExecute() {
			progressDlg = ProgressDialog.show(DownImage.this, "Wait",
					"Downloading...");
		}

		protected Bitmap doInBackground(String... strs) {
			URL url = null;
			BufferedInputStream bis = null;
			Bitmap bitmap = null;
			try {
				url = new URL(strs[0]);
				HttpURLConnection con = (HttpURLConnection) url
						.openConnection();
				bis = new BufferedInputStream(con.getInputStream());
				bitmap = BitmapFactory.decodeStream(bis);
				bis.close();
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return bitmap;
		}

		protected void onPostExecute(Bitmap result) {
			progressDlg.dismiss();
			imageView.setImageBitmap(result);
		}
	}// end of class ImageLoadingTask
}// end of class RemoteImage

